import 'package:flutter/material.dart';
import 'package:flutter_im_demo/state/global_state.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import '../const_value.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _phoneController = TextEditingController();
  final _passwordController = TextEditingController();

  final GlobalKey _formKey = GlobalKey<FormState>();

  bool _showPassword = false;

  @override
  Widget build(BuildContext context) {
    final inputBorder =
        OutlineInputBorder(borderRadius: BorderRadius.circular(8.0));
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Colors.grey,
            ),
            onPressed: () => Navigator.of(context).pop()),
      ),
      body: Consumer<GlobalState>(builder: (context, state, _) {
//        return InkWell(
//          onTap: () async {
//            bool isLogin = await state.login("110", "123");
//            if(isLogin) {
//              Navigator.of(context).pop();
//            }
//          },
//          child: Center(
//            child: Text("Login Page, errorMsg: ${state.errorMsg?.toString()}, "
//                "user: ${state.userInfoModel?.toString()}"),
//          ),
//        );
        return SingleChildScrollView(
          child: Padding(
            padding:
                const EdgeInsets.symmetric(vertical: 14.0, horizontal: 16.0),
            child: Form(
              key: _formKey, //设置globalKey，用于后面获取FormState
              autovalidate: true,
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const Text("登 录",
                        style: TextStyle(
                            fontSize: 26.0, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 40.0),
                    TextFormField(
                      autofocus: false,
                      maxLines: 1,
                      controller: _phoneController,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.all(18.0),
                        border: inputBorder,
                        labelText: "手机号",
                        hintText: "",
                      ),
                      validator: (v) {
                        return v.trim().length > 0 && isChinaPhoneLegal(v)
                            ? null
                            : "请填写手机号";
                      },
                    ),
                    const SizedBox(height: 50.0),
                    TextFormField(
                      autofocus: false,
                      obscureText: !_showPassword,
                      maxLines: 1,
                      controller: _passwordController,
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.all(18.0),
                        border: inputBorder,
                        labelText: "密码",
                        hintText: "6~16位数字和字符组合",
                        suffixIcon: IconButton(
                            icon: Icon(
                              _showPassword
                                  ? FontAwesomeIcons.eyeSlash
                                  : FontAwesomeIcons.eye,
                              size: 16.0,
                              color: Colors.grey,
                            ),
                            onPressed: _showPasswordFun)),
                      validator: (v) {
                        return v.trim().length > 0 && isLoginPassword(v)
                            ? null
                            : "请输入正确密码";
                      },
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        FlatButton(
                          child: Text("忘记密码?"),
                          onPressed: () {},
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 40.0,
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 15.0),
                      child: Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          InkWell(
                            onTap: () => _onLogin(state),
                            child: Container(
                              width: 50.0,
                              height: 50.0,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(60.0),
                                  gradient: gradientColor),
                              child: Icon(
                                Icons.arrow_forward,
                                color: Colors.white,
                              ),
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      }),
    );
  }

  void _onLogin(GlobalState state) async {
    if ((_formKey.currentState as FormState).validate()) {
      print(
          "校验通过, phone: ${_phoneController.text} password: ${_passwordController.text}");
      bool isLogin =
          await state.login(_phoneController.text, _passwordController.text);
      if (isLogin) {
        Navigator.of(context).pop();
      }
    }
  }

  static bool isChinaPhoneLegal(String str) {
    return new RegExp(
            '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$')
        .hasMatch(str);
  }

  static bool isLoginPassword(String input) {
    RegExp mobile = new RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
    return mobile.hasMatch(input);
  }

  void _showPasswordFun() {
    if (_passwordController.text.isEmpty) return;
    setState(() {
      _showPassword = !_showPassword;
    });
  }
}
